<!DOCTYPE html>
<html lang="">
    <!-- title -->




<!-- keywords -->




<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="author" content="Eric">
    <meta name="renderer" content="webkit">
    <meta name="copyright" content="Eric">
    
    <meta name="keywords" content="hexo,hexo-theme,hexo-blog">
    
    <meta name="description" content="">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>多线程与高并发-可见性|顺序性|原子性 · VIK&#39;s blog</title>
    <style type="text/css">
    @font-face {
        font-family: 'Oswald-Regular';
        src: url("/blog/font/Oswald-Regular.ttf");
    }

    body {
        margin: 0;
    }

    header,
    footer,
    .back-top,
    .sidebar,
    .container,
    .site-intro-meta,
    .toc-wrapper {
        display: none;
    }

    .site-intro {
        position: relative;
        z-index: 3;
        width: 100%;
        /* height: 50vh; */
        overflow: hidden;
    }

    .site-intro-placeholder {
        position: absolute;
        z-index: -2;
        top: 0;
        left: 0;
        width: calc(100% + 300px);
        height: 100%;
        background: repeating-linear-gradient(-45deg, #444 0, #444 80px, #333 80px, #333 160px);
        background-position: center center;
        transform: translate3d(-226px, 0, 0);
        animation: gradient-move 2.5s ease-out 0s infinite;
    }

    @keyframes gradient-move {
        0% {
            transform: translate3d(-226px, 0, 0);
        }
        100% {
            transform: translate3d(0, 0, 0);
        }
    }

</style>

    <link rel="preload" href="/blog/css/style.css?v=20180824" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <link rel="stylesheet" href="/blog/css/mobile.css?v=20180824" media="(max-width: 980px)">
    
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    
    <!-- /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
/* This file is meant as a standalone workflow for
- testing support for link[rel=preload]
- enabling async CSS loading in browsers that do not support rel=preload
- applying rel preload css once loaded, whether supported or not.
*/ -->
<script>
(function( w ){
	"use strict";
	// rel=preload support test
	if( !w.loadCSS ){
		w.loadCSS = function(){};
	}
	// define on the loadCSS obj
	var rp = loadCSS.relpreload = {};
	// rel=preload feature support test
	// runs once and returns a function for compat purposes
	rp.support = (function(){
		var ret;
		try {
			ret = w.document.createElement( "link" ).relList.supports( "preload" );
		} catch (e) {
			ret = false;
		}
		return function(){
			return ret;
		};
	})();

	// if preload isn't supported, get an asynchronous load by using a non-matching media attribute
	// then change that media back to its intended value on load
	rp.bindMediaToggle = function( link ){
		// remember existing media attr for ultimate state, or default to 'all'
		var finalMedia = link.media || "all";

		function enableStylesheet(){
			link.media = finalMedia;
		}

		// bind load handlers to enable media
		if( link.addEventListener ){
			link.addEventListener( "load", enableStylesheet );
		} else if( link.attachEvent ){
			link.attachEvent( "onload", enableStylesheet );
		}

		// Set rel and non-applicable media type to start an async request
		// note: timeout allows this to happen async to let rendering continue in IE
		setTimeout(function(){
			link.rel = "stylesheet";
			link.media = "only x";
		});
		// also enable media after 3 seconds,
		// which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
		setTimeout( enableStylesheet, 3000 );
	};

	// loop through link elements in DOM
	rp.poly = function(){
		// double check this to prevent external calls from running
		if( rp.support() ){
			return;
		}
		var links = w.document.getElementsByTagName( "link" );
		for( var i = 0; i < links.length; i++ ){
			var link = links[ i ];
			// qualify links to those with rel=preload and as=style attrs
			if( link.rel === "preload" && link.getAttribute( "as" ) === "style" && !link.getAttribute( "data-loadcss" ) ){
				// prevent rerunning on link
				link.setAttribute( "data-loadcss", true );
				// bind listeners to toggle media back
				rp.bindMediaToggle( link );
			}
		}
	};

	// if unsupported, run the polyfill
	if( !rp.support() ){
		// run once at least
		rp.poly();

		// rerun poly on an interval until onload
		var run = w.setInterval( rp.poly, 500 );
		if( w.addEventListener ){
			w.addEventListener( "load", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		} else if( w.attachEvent ){
			w.attachEvent( "onload", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		}
	}


	// commonjs
	if( typeof exports !== "undefined" ){
		exports.loadCSS = loadCSS;
	}
	else {
		w.loadCSS = loadCSS;
	}
}( typeof global !== "undefined" ? global : this ) );
</script>

    <link rel="icon" href="/blog/assets/favicon.jpg">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js" as="script">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js" as="script">
    <link rel="preload" href="/blog/scripts/main.js" as="script">
    <link rel="preload" as="font" href="/blog/font/Oswald-Regular.ttf" crossorigin="">
    <link rel="preload" as="font" href="https://at.alicdn.com/t/font_327081_1dta1rlogw17zaor.woff" crossorigin="">
    
    <!-- fancybox -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" defer></script>
    <!-- 百度统计  -->
    
    <!-- 谷歌统计  -->
    
</head>

    
        <body class="post-body">
    
    
<header class="header">

    <div class="read-progress"></div>
    <div class="header-sidebar-menu">&#xe775;</div>
    <!-- post页的toggle banner  -->
    
    <div class="banner">
            <div class="blog-title">
                <a href="/blog/">VIK&#39;s blog</a>
            </div>
            <div class="post-title">
                <a href="#" class="post-name">多线程与高并发-可见性|顺序性|原子性</a>
            </div>
    </div>
    
    <a class="home-link" href="/blog/">VIK's blog</a>
</header>
    <div class="wrapper">
        <div class="site-intro" style="







height:50vh;
">
    
    <!-- 主页  -->
    
    
    <!-- 404页  -->
            
    <div class="site-intro-placeholder"></div>
    <div class="site-intro-img" style="background-image: url(/blog/intro/post-bg.jpg)"></div>
    <div class="site-intro-meta">
        <!-- 标题  -->
        <h1 class="intro-title">
            <!-- 主页  -->
            
            多线程与高并发-可见性|顺序性|原子性
            <!-- 404 -->
            
        </h1>
        <!-- 副标题 -->
        <p class="intro-subtitle">
            <!-- 主页副标题  -->
            
            
            <!-- 404 -->
            
        </p>
        <!-- 文章页meta -->
        
            <div class="post-intros">
                <!-- 文章页标签  -->
                
                    <div class="post-intro-tags">
    
        <a class="post-tag" href="javascript:void(0);" data-tags="多线程与高并发">多线程与高并发</a>
    
</div>
                
                
                    <div class="post-intro-read">
                        <span>字数统计: <span class="post-count word-count">1.6k</span>阅读时长: <span class="post-count reading-time">5 min</span></span>
                    </div>
                
                <div class="post-intro-meta">
                    <span class="post-intro-calander iconfont-archer">&#xe676;</span>
                    <span class="post-intro-time">2020/11/16</span>
                    
                    <span id="busuanzi_container_page_pv" class="busuanzi-pv">
                        <span class="iconfont-archer">&#xe602;</span>
                        <span id="busuanzi_value_page_pv"></span>
                    </span>
                    
                    <span class="shareWrapper">
                        <span class="iconfont-archer shareIcon">&#xe71d;</span>
                        <span class="shareText">Share</span>
                        <ul class="shareList">
                            <li class="iconfont-archer share-qr" data-type="qr">&#xe75b;
                                <div class="share-qrcode"></div>
                            </li>
                            <li class="iconfont-archer" data-type="weibo">&#xe619;</li>
                            <li class="iconfont-archer" data-type="qzone">&#xe62e;</li>
                            <li class="iconfont-archer" data-type="twitter">&#xe634;</li>
                            <li class="iconfont-archer" data-type="facebook">&#xe67a;</li>
                        </ul>
                    </span>
                </div>
            </div>
        
    </div>
</div>
        <script>
 
  // get user agent
  var browser = {
    versions: function () {
      var u = window.navigator.userAgent;
      return {
        userAgent: u,
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
        iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
        iPad: u.indexOf('iPad') > -1, //是否为iPad
        webApp: u.indexOf('Safari') == -1, //是否为web应用程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') == -1, //是否为微信浏览器
        uc: u.indexOf('UCBrowser') > -1 //是否为android下的UC浏览器
      };
    }()
  }
  console.log("userAgent:" + browser.versions.userAgent);

  // callback
  function fontLoaded() {
    console.log('font loaded');
    if (document.getElementsByClassName('site-intro-meta')) {
      document.getElementsByClassName('intro-title')[0].classList.add('intro-fade-in');
      document.getElementsByClassName('intro-subtitle')[0].classList.add('intro-fade-in');
      var postIntros = document.getElementsByClassName('post-intros')[0]
      if (postIntros) {
        postIntros.classList.add('post-fade-in');
      }
    }
  }

  // UC不支持跨域，所以直接显示
  function asyncCb(){
    if (browser.versions.uc) {
      console.log("UCBrowser");
      fontLoaded();
    } else {
      WebFont.load({
        custom: {
          families: ['Oswald-Regular']
        },
        loading: function () {  //所有字体开始加载
          // console.log('loading');
        },
        active: function () {  //所有字体已渲染
          fontLoaded();
        },
        inactive: function () { //字体预加载失败，无效字体或浏览器不支持加载
          console.log('inactive: timeout');
          fontLoaded();
        },
        timeout: 5000 // Set the timeout to two seconds
      });
    }
  }

  function asyncErr(){
    console.warn('script load from CDN failed, will load local script')
  }

  // load webfont-loader async, and add callback function
  function async(u, cb, err) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (cb) { o.addEventListener('load', function (e) { cb(null, e); }, false); }
    if (err) { o.addEventListener('error', function (e) { err(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }

  var asyncLoadWithFallBack = function(arr, success, reject) {
      var currReject = function(){
        reject()
        arr.shift()
        if(arr.length)
          async(arr[0], success, currReject)
        }

      async(arr[0], success, currReject)
  }

  asyncLoadWithFallBack([
    "https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js", 
    "https://cdn.bootcss.com/webfont/1.6.28/webfontloader.js",
    "/blog/lib/webfontloader.min.js"
  ], asyncCb, asyncErr)
</script>        
        <img class="loading" src="/blog/assets/loading.svg" style="display: block; margin: 6rem auto 0 auto; width: 6rem; height: 6rem;" />
        <div class="container container-unloaded">
            <main class="main post-page">
    <article class="article-entry">
        <p>[toc]    </p>
<p>​    谈到多线程与高并发，总是离不开原子性、可见性和一致性。本文就来分析一下这三种特性的一些包括涉及计算机底层的知识点。</p>
<h2 id="1-原子性-Atomic"><a href="#1-原子性-Atomic" class="headerlink" title="1. 原子性(Atomic)"></a>1. 原子性(Atomic)</h2><h3 id="什么是原子性？"><a href="#什么是原子性？" class="headerlink" title="什么是原子性？"></a>什么是原子性？</h3><p>原子性提供了互斥访问，同一时刻只能有一个线程可以对它进行操作。</p>
<h3 id="破坏原子性的例子"><a href="#破坏原子性的例子" class="headerlink" title="破坏原子性的例子"></a>破坏原子性的例子</h3><p>比如说 n++的操作，看似是一条原子性的操作，但是如果多线程进行同样的n++操作。</p>
<p>n++在jvm字节码中，其实是拆分成了多条字节码。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AtomicTest</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> n;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">m</span><span class="params">()</span></span>&#123;</span><br><span class="line">        n++;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">利用idea的插件 jclasslib可以看到以下字节码</span><br><span class="line">0 aload_0  #装载this</span><br><span class="line"> 1 dup     #复制一份this并压栈</span><br><span class="line"> 2 getfield #2 &lt;com/test/AtomicTest.n&gt;  #获取成员变量n的值0</span><br><span class="line"> 5 iconst_1  #把 1 压栈</span><br><span class="line"> 6 iadd		# 执行 0+1操作</span><br><span class="line"> 7 putfield #2 &lt;com/test/AtomicTest.n&gt;  #把add之后的值赋值到n</span><br><span class="line">10 return  #返回函数调用</span><br></pre></td></tr></table></figure>
<p>由上可以看出来，n++并不是由一条汇编代码完成的操作，所以并不保证原子性</p>
<h3 id="怎么保证原子性"><a href="#怎么保证原子性" class="headerlink" title="怎么保证原子性"></a>怎么保证原子性</h3><h4 id="synchronized加锁"><a href="#synchronized加锁" class="headerlink" title="synchronized加锁"></a>synchronized加锁</h4><ul>
<li><p>synchronized是可重入锁，<strong>可重入锁</strong> 即同线程内已经获得锁，再次获取锁的时候，并不会出现死锁</p>
</li>
<li><p>不可中断，只要synchronized不释放，其他线程无法获取锁</p>
</li>
<li><p>在HotSpot虚拟机中的实现: 锁定对象存储的 mark-word锁类型标记中，占用了前三个比特位来表示锁状态</p>
<p>| 偏向锁标识位 | 锁标识位 | 锁状态   | 存储内容                     |<br>| ———— | ——– | ——– | —————————- |<br>| 0            | 01       | 未锁定   | hash code(31),年龄(4)        |<br>| 1            | 01       | 偏向锁   | 线程ID(54),时间戳(2),年龄(4) |<br>| 无           | 00       | 轻量级锁 | 栈中锁记录的指针(64)         |<br>| 无           | 10       | 重量级锁 | monitor的指针(64)            |<br>| 无           | 11       | GC标记   | 空，不需要记录信息           |</p>
</li>
<li><p>不要去锁 Integer、String、Long，因为每次锁住的可能都是不同的对象实例</p>
<ul>
<li>Integer  -128~127 区间外，每次都会new一个新的Integer对象</li>
</ul>
</li>
<li><p>synchronized保证原子性和可见性，但<strong>不保证有序性</strong></p>
</li>
</ul>
<h4 id="CAS-compare-and-swap"><a href="#CAS-compare-and-swap" class="headerlink" title="CAS(compare and swap)"></a>CAS(compare and swap)</h4><ul>
<li>循环尝试，总有一次能成功 ！！但是消耗CPU资源！！</li>
<li>乐观锁/无锁</li>
<li>底层调用 Unsafe-&gt; compareAndSwapXXX(native方法)，本身具有原子性</li>
<li><strong>ABA问题</strong>(你女朋友已经不是之前的那个女朋友)</li>
<li>CAS例子<ul>
<li>AutomicXXX ， 比如 AutomicInteger()</li>
</ul>
</li>
<li>不能保证代码块的原子性</li>
</ul>
<h2 id="2-可见性"><a href="#2-可见性" class="headerlink" title="2. 可见性"></a>2. 可见性</h2><h3 id="CPU缓存导致的可见性问题"><a href="#CPU缓存导致的可见性问题" class="headerlink" title="CPU缓存导致的可见性问题"></a>CPU缓存导致的可见性问题</h3><p>​    CPU执行操作数据首先会从内存把数据拷贝到CPU缓存区，然后再对缓存里的数据进行更新等操作，最后CPU才会把缓存里数据更新到内存。这就会导致多个CPU间共享同样的数据的时候，无法及时觉察到其他线程对数据的修改。</p>
<p>​    缓存行的存在。</p>
<h3 id="如何保证可见性"><a href="#如何保证可见性" class="headerlink" title="如何保证可见性"></a>如何保证可见性</h3><h4 id="缓存一致性协议"><a href="#缓存一致性协议" class="headerlink" title="缓存一致性协议"></a>缓存一致性协议</h4><ul>
<li>四个状态 M E  S I<ul>
<li>M: modified, 代表该缓存内容被修改了</li>
<li>E: exclusive, 代表该缓存行对应内存中的内容只被该CPU缓存</li>
<li>S: shared, 数据不止存在本地CPU缓存中，还存在别的CPU的缓存中</li>
<li>I : invalid，代表该缓存行中的内容已经失效</li>
</ul>
</li>
<li><p>为什么要有MESI协议: 因为早期的锁总线的方式效率低下</p>
</li>
<li><p>核心的思想：当CPU写数据时，如果发现操作的变量是共享变量，即在其他CPU中也存在该变量的副本，会发出信号通知其他CPU将该变量的缓存行置为无效状态</p>
</li>
</ul>
<h4 id="volatile"><a href="#volatile" class="headerlink" title="volatile"></a>volatile</h4><ul>
<li>被volatile修饰的变量，在使用的时候，CPU会强制从主存中读取最新的值</li>
<li>可以理解为，取消了jvm中对volatile变量的缓存</li>
<li>底层 jvm生成带 lock前缀的指令</li>
</ul>
<h2 id="3-顺序性"><a href="#3-顺序性" class="headerlink" title="3. 顺序性"></a>3. 顺序性</h2><h3 id="破坏顺序性的原因"><a href="#破坏顺序性的原因" class="headerlink" title="破坏顺序性的原因"></a>破坏顺序性的原因</h3><p>程序往往不是按照代码中的顺序来执行的。原因有以下</p>
<ul>
<li>编译器优化</li>
<li>CPU优化</li>
</ul>
<blockquote>
<p>好比洗水壶、烧开水、洗茶壶、洗茶杯、泡茶，如果完全按顺序的话，会浪费很多时间，可以在烧开水的时候洗茶杯、洗水壶。</p>
</blockquote>
<ul>
<li>总的来说，原因是为了提高CPU的性能</li>
</ul>
<h3 id="volatile-防止指令重排"><a href="#volatile-防止指令重排" class="headerlink" title="volatile 防止指令重排"></a>volatile 防止指令重排</h3><p>volatile除了保证可见性的同时，也保证了顺序性。</p>
<p>顺序性 <strong>即程序执行的顺序按照代码的先后顺序执行</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public class Test &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        Test t  = new Test();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">0 new #2 &lt;com/Test&gt;</span><br><span class="line">3 dup</span><br><span class="line">4 invokespecial #3 &lt;com/Test.&lt;init&gt;&gt;</span><br><span class="line">7 astore_1</span><br><span class="line">8 return</span><br></pre></td></tr></table></figure>
<p>以上如果发生指令重排，即 7 astore_1和 4invokespecial顺序换了，则会出问题。比如单例double check中未加入volatile。</p>
<h3 id="内存屏障"><a href="#内存屏障" class="headerlink" title="内存屏障"></a>内存屏障</h3><blockquote>
<p><a href="https://blog.csdn.net/ly262173911/article/details/106063924" target="_blank" rel="noopener">https://blog.csdn.net/ly262173911/article/details/106063924</a> 参考该链接</p>
</blockquote>
<p>内存屏障分为读屏障(load barrier)和写屏障(write barrier)</p>
<p>内存屏障的作用</p>
<blockquote>
<p> <strong>1.阻止屏障两侧的指令重排序；</strong><br><strong>2.强制把写缓冲区/高速缓存中的脏数据等写回主内存，让缓存中相应的数据失效。</strong></p>
</blockquote>
<ul>
<li><p>对于Load Barrier来说，在指令前插入Load Barrier，可以让高速缓存中的数据失效，强制从新从主内存加载数据；</p>
</li>
<li><p>对于Store Barrier来说，在指令后插入Store Barrier，能让写入缓存中的最新数据更新写入主内存，让其他线程可见。</p>
</li>
</ul>
<ul>
<li>LoadLoad</li>
</ul>
<p>load1；LoadLoad；load2</p>
<p>保证load1的数据加载先于load2及其后续所有load指令的数据加载</p>
<ul>
<li>StoreStore</li>
</ul>
<p>store1；StoreStore；store2</p>
<p>保证store1写入到数据对其他处理器可见（即刷新到内存）要先于store2及其后续store指令的写入</p>
<ul>
<li>LoadStore</li>
</ul>
<p>load1；LoadStore；store2</p>
<p>保证load1加载的数据先于store2以及其后store指令对数据的写入</p>
<ul>
<li>StoreLoad</li>
</ul>
<p>store1；StoreLoad；load2</p>
<p>保证store1写入的数据对其他处理器可见（即刷新到内存）要先于load2及其后续load指令对数据的加载</p>
<p>最后的StoreLoad屏障是开销最昂贵的一种屏障，其中一部分原因是因为他需要把写缓冲区的所有数据全部刷新到内存。</p>
<blockquote>
<p><strong>在每个volatile写操作前插入StoreStore屏障，在写操作后插入StoreLoad屏障；<br>在每个volatile读操作前插入LoadLoad屏障，在读操作后插入LoadStore屏障；</strong></p>
</blockquote>

    </article>
    <!-- license  -->
    
        <div class="license-wrapper">
            <p>原文作者：<a href="http://fantastyj.gitee.io/blog">Eric</a>
            </p><p>原文链接：<a href="http://fantastyj.gitee.io/blog/2020/11/16/多线程与高并发-可见性-顺序性-原子性/">http://fantastyj.gitee.io/blog/2020/11/16/多线程与高并发-可见性-顺序性-原子性/</a>
            </p><p>发表日期：<a href="http://fantastyj.gitee.io/blog/2020/11/16/多线程与高并发-可见性-顺序性-原子性/">November 16th 2020, 8:04:30 pm</a>
            </p><p>更新日期：<a href="http://fantastyj.gitee.io/blog/2020/11/16/多线程与高并发-可见性-顺序性-原子性/">November 16th 2020, 9:51:58 pm</a>
            </p><p>版权声明：本文采用<a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可</p>
        </div>
    
    <!-- paginator  -->
    <ul class="post-paginator">
        <li class="next">
            
                <div class="nextSlogan">Next Post</div>
                <a href="/blog/2020/11/20/多线程与高并发-CAS-AQS源码分析/" title="多线程与高并发-CAS&AQS源码分析">
                    <div class="nextTitle">多线程与高并发-CAS&AQS源码分析</div>
                </a>
            
        </li>
        <li class="previous">
            
                <div class="prevSlogan">Previous Post</div>
                <a href="/blog/2020/11/11/设计模式-代理模式/" title="设计模式-代理模式">
                    <div class="prevTitle">设计模式-代理模式</div>
                </a>
            
        </li>
    </ul>
    <!-- 评论插件 -->
    <!-- 来必力City版安装代码 -->

<!-- City版安装代码已完成 -->
    
    
    <!-- partial('_partial/comment/changyan') -->
    <!--PC版-->


    
    
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
    <div id="comment"></div>
    <script>
    new Valine({
        el: '#comment' ,
        notify:false, 
        verify:false, 
        appId: "xsrAgYKsf6uAaBjhBNhCnzTC-9Nh9j0Va",
        appKey: "MRd2L7iitgfwOndKkXrnxCUs",
        placeholder: "欢迎留言分享和讨论~",
        path:window.location.pathname, 
        avatar:'mm' 
    });
    </script>


    <!-- 评论 -->
</main>
            <!-- profile -->
            
        </div>
        <footer class="footer footer-unloaded">
    <!-- social  -->
    
    <div class="social">
        
    
        
            
                <a href="mailto:465612025@qq.com" class="iconfont-archer email" title="email"></a>
            
        
    
        
            
                <a href="//github.com/WhoamiV" class="iconfont-archer github" target="_blank" title="github"></a>
            
        
    
        
            
                <span class="iconfont-archer wechat" title="wechat">
                  
                  <img class="profile-qr" src="/blog/assets/wechat_qr_code.png">
                </span>
            
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
    

    </div>
    
    <!-- powered by Hexo  -->
    <div class="copyright">
        <span id="hexo-power">Powered by <a href="https://hexo.io/" target="_blank">Hexo</a></span><span class="iconfont-archer power">&#xe635;</span><span id="theme-info">theme <a href="https://github.com/fi3ework/hexo-theme-archer" target="_blank">Archer</a></span>
    </div>
    <!-- 不蒜子  -->
    
    <div class="busuanzi-container">
    
     
    <span id="busuanzi_container_site_pv">PV: <span id="busuanzi_value_site_pv"></span> :)</span>
    
    </div>
    
</footer>
    </div>
    <!-- toc -->
    
    <div class="toc-wrapper" style=
    







top:50vh;

    >
        <div class="toc-catalog">
            <span class="iconfont-archer catalog-icon">&#xe613;</span><span>CATALOG</span>
        </div>
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-原子性-Atomic"><span class="toc-number">1.</span> <span class="toc-text">1. 原子性(Atomic)</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#什么是原子性？"><span class="toc-number">1.1.</span> <span class="toc-text">什么是原子性？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#破坏原子性的例子"><span class="toc-number">1.2.</span> <span class="toc-text">破坏原子性的例子</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#怎么保证原子性"><span class="toc-number">1.3.</span> <span class="toc-text">怎么保证原子性</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#synchronized加锁"><span class="toc-number">1.3.1.</span> <span class="toc-text">synchronized加锁</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#CAS-compare-and-swap"><span class="toc-number">1.3.2.</span> <span class="toc-text">CAS(compare and swap)</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-可见性"><span class="toc-number">2.</span> <span class="toc-text">2. 可见性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#CPU缓存导致的可见性问题"><span class="toc-number">2.1.</span> <span class="toc-text">CPU缓存导致的可见性问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#如何保证可见性"><span class="toc-number">2.2.</span> <span class="toc-text">如何保证可见性</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#缓存一致性协议"><span class="toc-number">2.2.1.</span> <span class="toc-text">缓存一致性协议</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#volatile"><span class="toc-number">2.2.2.</span> <span class="toc-text">volatile</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-顺序性"><span class="toc-number">3.</span> <span class="toc-text">3. 顺序性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#破坏顺序性的原因"><span class="toc-number">3.1.</span> <span class="toc-text">破坏顺序性的原因</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#volatile-防止指令重排"><span class="toc-number">3.2.</span> <span class="toc-text">volatile 防止指令重排</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#内存屏障"><span class="toc-number">3.3.</span> <span class="toc-text">内存屏障</span></a></li></ol></li></ol>
    </div>
    
    <div class="back-top iconfont-archer">&#xe639;</div>
    <div class="sidebar sidebar-hide">
    <ul class="sidebar-tabs sidebar-tabs-active-0">
        <li class="sidebar-tab-archives"><span class="iconfont-archer">&#xe67d;</span><span class="tab-name">Archive</span></li>
        <li class="sidebar-tab-tags"><span class="iconfont-archer">&#xe61b;</span><span class="tab-name">Tag</span></li>
        <li class="sidebar-tab-categories"><span class="iconfont-archer">&#xe666;</span><span class="tab-name">Cate</span></li>
    </ul>
    <div class="sidebar-content sidebar-content-show-archive">
          <div class="sidebar-panel-archives">
    <!-- 在ejs中将archive按照时间排序 -->
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    <div class="total-and-search">
        <div class="total-archive">
        Total : 18
        </div>
        <!-- search  -->
        
    </div>
    
    <div class="post-archive">
    
    
    
    
    <div class="archive-year"> 2020 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/11</span><a class="archive-post-title" href="/blog/2020/12/11/多线程与高并发-JUC死锁/">多线程与高并发-JUC死锁</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/05</span><a class="archive-post-title" href="/blog/2020/12/05/多线程与高并发-JUC之原子类-同步锁/">多线程与高并发-JUC之原子类&同步锁</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">11/26</span><a class="archive-post-title" href="/blog/2020/11/26/设计模式-责任链模式/">设计模式-责任链模式</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">11/20</span><a class="archive-post-title" href="/blog/2020/11/20/多线程与高并发-CAS-AQS源码分析/">多线程与高并发-CAS&AQS源码分析</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">11/16</span><a class="archive-post-title" href="/blog/2020/11/16/多线程与高并发-可见性-顺序性-原子性/">多线程与高并发-可见性|顺序性|原子性</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">11/11</span><a class="archive-post-title" href="/blog/2020/11/11/设计模式-代理模式/">设计模式-代理模式</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">11/07</span><a class="archive-post-title" href="/blog/2020/11/07/设计模式-工厂模式/">设计模式-工厂模式</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2019 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/03</span><a class="archive-post-title" href="/blog/2019/03/03/Mysql死锁分析/">Mysql死锁分析</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">02/23</span><a class="archive-post-title" href="/blog/2019/02/23/Phoenix部署及应用/">Phoenix部署及应用</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">02/20</span><a class="archive-post-title" href="/blog/2019/02/20/JStorm部署及应用/">JStorm部署及应用</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2018 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/26</span><a class="archive-post-title" href="/blog/2018/12/26/Storm分布式实时计算框架详解/">Storm分布式实时计算框架详解</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/19</span><a class="archive-post-title" href="/blog/2018/12/19/docker-搭建MongoDb/">docker-搭建MongoDb</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/19</span><a class="archive-post-title" href="/blog/2018/12/19/docker-搭建Mysql/">docker-搭建Mysql</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/15</span><a class="archive-post-title" href="/blog/2018/12/15/git使用总结/">git使用总结</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/13</span><a class="archive-post-title" href="/blog/2018/12/13/linux常用指令分类汇总/">linux常用指令分类汇总</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/13</span><a class="archive-post-title" href="/blog/2018/12/13/HBase之Springboot操作指南/">HBase之Springboot操作指南</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/06</span><a class="archive-post-title" href="/blog/2018/12/06/Hadoop架构分析与实战操作/">Hadoop架构分析与实战操作</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">12/06</span><a class="archive-post-title" href="/blog/2018/12/06/Hadoop+HBase集群搭建/">Hadoop+HBase高可用集群搭建</a>
        </li>
    
    </ul></div>
  </div>
        <div class="sidebar-panel-tags">
    <div class="sidebar-tags-name">
    
        <span class="sidebar-tag-name" data-tags="hadoop"><span class="iconfont-archer">&#xe606;</span>hadoop</span>
    
        <span class="sidebar-tag-name" data-tags="storm"><span class="iconfont-archer">&#xe606;</span>storm</span>
    
        <span class="sidebar-tag-name" data-tags="docker"><span class="iconfont-archer">&#xe606;</span>docker</span>
    
        <span class="sidebar-tag-name" data-tags="tools"><span class="iconfont-archer">&#xe606;</span>tools</span>
    
        <span class="sidebar-tag-name" data-tags="mysql"><span class="iconfont-archer">&#xe606;</span>mysql</span>
    
        <span class="sidebar-tag-name" data-tags="linux"><span class="iconfont-archer">&#xe606;</span>linux</span>
    
        <span class="sidebar-tag-name" data-tags="多线程与高并发"><span class="iconfont-archer">&#xe606;</span>多线程与高并发</span>
    
        <span class="sidebar-tag-name" data-tags="设计模式"><span class="iconfont-archer">&#xe606;</span>设计模式</span>
    
    </div>
    <div class="iconfont-archer sidebar-tags-empty">&#xe678;</div>
    <div class="tag-load-fail" style="display: none; color: #ccc; font-size: 0.6rem;">
    缺失模块。<br>
    1、请确保node版本大于6.2<br>
    2、在博客根目录（注意不是archer根目录）执行以下命令：<br>
    <span style="color: #f75357; font-size: 1rem; line-height: 2rem;">npm i hexo-generator-json-content --save</span><br>
    3、在根目录_config.yml里添加配置：
    <pre style="color: #787878; font-size: 0.6rem;">
jsonContent:
  meta: false
  pages: false
  posts:
    title: true
    date: true
    path: true
    text: false
    raw: false
    content: false
    slug: false
    updated: false
    comments: false
    link: false
    permalink: false
    excerpt: false
    categories: true
    tags: true</pre>
    </div> 
    <div class="sidebar-tags-list"></div>
</div>
        <div class="sidebar-panel-categories">
    <div class="sidebar-categories-name">
    
    </div>
    <div class="iconfont-archer sidebar-categories-empty">&#xe678;</div>
    <div class="sidebar-categories-list"></div>
</div>
    </div>
</div> 
    <script>
    var siteMeta = {
        root: "/blog/",
        author: "Eric"
    }
</script>
    <!-- CDN failover -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
    <script type="text/javascript">
        if (typeof window.$ === 'undefined')
        {
            console.warn('jquery load from jsdelivr failed, will load local script')
            document.write('<script src="/blog/lib/jquery.min.js">\x3C/script>')
        }
    </script>
    <script src="/blog/scripts/main.js"></script>
    <!-- algolia -->
    
    <!-- busuanzi  -->
    
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    
    <!-- CNZZ  -->
    
    </div>
    <!-- async load share.js -->
    
        <script src="/blog/scripts/share.js" async></script>    
     
    </body>
</html>


